package com.walming.generator.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author walming
 * @date 2020-11-25 13:58
 */
public class StringSeriesValidator implements ConstraintValidator<StringSeries, String> {

    private StringSeries series;

    @Override
    public void initialize(StringSeries series) {
        this.series = series;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || series.list().length <= 0) {
            return true;
        }

        StringBuilder message = new StringBuilder();
        for (String str : series.list()) {
            if (value.equals(str)) {
                return true;
            }
            if (message.length() > 0) {
                message.append(",");
            }
            message.append(str);
        }

        // 重置错误提示信息 message
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("数据不在{" + message + "}集合内").addConstraintViolation();
        return false;
    }

}
